﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;
using System.Web.Security;
using WxSDK;
using WxSDK.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using WxSDK.CacheSys;
namespace WxSDK
{
    /// <summary>
    /// 微信接收到的消息结合数据的处理
    /// </summary>
    public class WeChatEvent : System.Web.UI.Page
    {
        BLL.Wx_User bll_wx_user = new BLL.Wx_User();
        BLL.Wx_Message bll_wx_message = new BLL.Wx_Message();
        Model.wx_replay wx_replay = new Model.wx_replay();
        Model.wx_message wx_message = new Model.wx_message();
        //WeChatApi wxapi = new WeChatApi();

        #region 检测用户 - 接收用户
        /// <summary>
        /// 用户是否存在
        /// </summary>
        /// <param name="MemberId"></param>
        /// <param name="OpenId"></param>
        /// <returns></returns>
        private bool MemberExists(int MemberId, string OpenId)
        {
            return bll_wx_user.Exists(" MemberId=@0 and OpenId=@1 ", MemberId, OpenId);
        }
        /// <summary>
        /// 接收用户 , 用户不存在在数据库中添加  后期扩展  返回添加后用户ID
        /// </summary>
        /// <param name="MemberId"></param>
        /// <param name="openid"></param>
        private int RecivedUser(int MemberId, string openid)
        {

            if (!MemberExists(MemberId, openid)) //如果不存在用户
            {
                WeChatModel.userInfo UserInfo = WeChatApi.GetUserInfo(MemberId, openid); //从微信获取用户信息
                Model.wx_user wx_user = new Model.wx_user();
                wx_user.City = UserInfo.city;
                wx_user.Country = UserInfo.country;
                wx_user.Groupid = UserInfo.groupid;
                wx_user.HeadImgUrl = UserInfo.headimgurl;
                wx_user.Language = UserInfo.language;
                wx_user.LastMsgTime = DateTime.Now;
                wx_user.MemberId = MemberId;
                wx_user.NickName = UserInfo.nickname;
                wx_user.OpenId = UserInfo.openid;

                wx_user.ParentOpenId = "";

                wx_user.Province = UserInfo.province;
                wx_user.Remark = UserInfo.remark;
                wx_user.Sex = UserInfo.sex;
                wx_user.Source = "";
                wx_user.Subscribe = UserInfo.subscribe;
                wx_user.Subscribe_Time = UserInfo.subscribe_time;
                wx_user.Unionid = UserInfo.unionid;
                return bll_wx_user.Add(wx_user);
            }
            else { //如果存在用户
                return bll_wx_user.GetModel(string.Format(" where OpenId='{0}' and MemberId={1} ", openid, MemberId)).Id;
            }
        }
        #endregion

        /// <summary>
        /// 正常订阅
        /// </summary>
        /// <param name="MemberId"></param>
        /// <param name="model"></param>
        public void e_subscribe(int MemberId,WeChatModel.Event_Subscribe model) {
            //WeChatCommon.WirteFile("e_subscribe");
            int userid = RecivedUser(MemberId, model.FromUserName);
            if (userid>0) //存在用户
            {
                //默认生成一张临时二维码
                wx_member config = WeChatMemory.MemberInfo(MemberId);
                WeChatModel.qrTicket ticket = WeChatApi.getQRCode(config.QRCodeExp, userid, MemberId);
                string imgurl = string.Format(WeChat_Url.GetQrImgSrc, ticket.ticket);
                //WeChatCommon.WirteFile("e_subscribe+"+ticket.url);
                bll_wx_user.UpdateField(string.Format(" OpenId='{0}' ", model.FromUserName), " Subscribe=1,LastMsgTime=getdate(),QRUrl='" + imgurl + "',QR_WxUrl='" + ticket.url + "',QROutTime='" + (DateTime.Now.AddSeconds(ticket.expire_seconds - 7200)).ToString() + "' ");    
            }
        }

        /// <summary>
        /// 扫描带参数的二维码订阅
        /// </summary>
        /// <param name="MemberId"></param>
        /// <param name="model"></param>
        public void e_subscribe_para(int MemberId,WeChatModel.Event_SubscribePara model) {
            
            int userid = RecivedUser(MemberId, model.FromUserName);
            //WeChatCommon.WirteFile("e_subscribe_para+" + userid);
            if (userid > 0) //存在用户
            {
                //默认生成一张临时二维码
                wx_member config = WeChatMemory.MemberInfo(MemberId);
                WeChatModel.qrTicket ticket = WeChatApi.getQRCode(config.QRCodeExp, userid, MemberId);
                string imgurl = string.Format(WeChat_Url.GetQrImgSrc, ticket.ticket);
                //WeChatCommon.WirteFile("e_subscribe+" + model.FromUserName);
                bll_wx_user.UpdateField(string.Format(" OpenId='{0}' ", model.FromUserName), " Subscribe=1,LastMsgTime=getdate(),QRUrl='" + imgurl + "',QR_WxUrl='" + ticket.url + "',QROutTime='" + (DateTime.Now.AddSeconds(ticket.expire_seconds - 7200)).ToString() + "',Source='"+model.Ticket+"' ");
            }
            //bll_wx_user.UpdateField(string.Format(" OpenId='{0}' ", model.FromUserName), " Subscribe=1,LastMsgTime=getdate() ");
        }
        /// <summary>
        /// 取消订阅
        /// </summary>
        /// <param name="MemberId"></param>
        /// <param name="model"></param>
        public void e_unsubscribe(int MemberId, WeChatModel.Event_UnSubscribe model) {
            //WeChatCommon.WirteFile("e_unsubscribe");
            RecivedUser(MemberId, model.FromUserName);
            bll_wx_user.UpdateField(string.Format(" OpenId='{0}' ", model.FromUserName), " Subscribe=0,LastMsgTime=getdate() ");
        }
        /// <summary>
        /// 用户已经关注后扫描参数二维码
        /// </summary>
        /// <param name="MemberId"></param>
        /// <param name="model"></param>
        public void e_scan(int MemberId, WeChatModel.Event_Scan model)
        {
            //WeChatCommon.WirteFile("e_scan");
            int userid = RecivedUser(MemberId, model.FromUserName);
            if (userid > 0) //存在用户
            {
                //默认生成一张临时二维码
                wx_member config = WeChatMemory.MemberInfo(MemberId);
                WeChatModel.qrTicket ticket = WeChatApi.getQRCode(config.QRCodeExp, userid, MemberId);
                string imgurl = string.Format(WeChat_Url.GetQrImgSrc, ticket.ticket);
                //WeChatCommon.WirteFile("e_subscribe+" + model.FromUserName);
                bll_wx_user.UpdateField(string.Format(" OpenId='{0}' ", model.FromUserName), " Subscribe=1,LastMsgTime=getdate(),QRUrl='" + imgurl + "',QR_WxUrl='" + ticket.url + "',QROutTime='" + (DateTime.Now.AddSeconds(ticket.expire_seconds - 7200)).ToString() + "',Source='" + model.Ticket + "' ");
            }
        }
        /// <summary>
        /// 上报地理位置事件
        /// </summary>
        /// <param name="MemberId"></param>
        /// <param name="model"></param>
        public void e_location(int MemberId, WeChatModel.Event_Location model) {
            //WeChatCommon.WirteFile("e_location");
        }
        /// <summary>
        /// 点击菜单事件
        /// </summary>
        /// <param name="MemberId"></param>
        /// <param name="model"></param>
        public void e_click(int MemberId, WeChatModel.Event_Click model) {
            //WeChatCommon.WirteFile("e_click");
        }

        /// <summary>
        /// 此事件已经停止推送
        /// </summary>
        /// <param name="MemberId"></param>
        /// <param name="model"></param>
        public void e_view(int MemberId, WeChatModel.Event_View model) { }

        /// <summary>
        /// 模板消息发送完成后的事件推送
        /// </summary>
        /// <param name="MemberId"></param>
        /// <param name="model"></param>
        public void e_templatesendjobfinish(int MemberId , WeChatModel.Event_TemplateSendJobFinish model) {
            //WeChatCommon.WirteFile(model.Event);
        }

        #region 收到消息的处理程序 --保存消息
        public void m_text(int MemberId, WeChatModel.Msg_Txt model) {
            //WeChatCommon.WirteFile("m_text");
            wx_message.AddTime = WxSDK.WeChatCommon.ConvertIntDateTime(model.CreateTime);
            wx_message.MemberId = MemberId;
            wx_message.MsgCont = model.Content;
            wx_message.MsgType = 1;
            wx_message.OpenId = model.FromUserName;
            wx_message.ReplayCont = "";
            wx_message.ReplayType = 0;
            wx_message.MsgId = model.MsgId;
            bll_wx_message.Add(wx_message);
        }
        public void m_image(int MemberId, WeChatModel.Msg_Pic model) {
            //WeChatCommon.WirteFile("m_image");
            wx_message.AddTime = WxSDK.WeChatCommon.ConvertIntDateTime(model.CreateTime);
            wx_message.MemberId = MemberId;
            wx_message.MsgCont = model.MediaId;
            wx_message.MsgType = 2;
            wx_message.OpenId = model.FromUserName;
            wx_message.ReplayCont = "";
            wx_message.ReplayType = 0;
            wx_message.MsgId = model.MsgId;
            bll_wx_message.Add(wx_message);
        }
        public void m_voice(int MemberId, WeChatModel.Msg_Voice model) {
            //WeChatCommon.WirteFile("m_voice");
            wx_message.AddTime = WxSDK.WeChatCommon.ConvertIntDateTime(model.CreateTime);
            wx_message.MemberId = MemberId;
            wx_message.MsgCont = model.MediaId;
            wx_message.MsgType = 3;
            wx_message.OpenId = model.FromUserName;
            wx_message.ReplayCont = "";
            wx_message.ReplayType = 0;
            wx_message.MsgId = model.MsgID;
            bll_wx_message.Add(wx_message);
        }
        public void m_video(int MemberId, WeChatModel.Msg_Video model) {
            //WeChatCommon.WirteFile("m_video");
            wx_message.AddTime = WxSDK.WeChatCommon.ConvertIntDateTime(model.CreateTime);
            wx_message.MemberId = MemberId;
            wx_message.MsgCont = model.MediaId;
            wx_message.MsgType = 4;
            wx_message.OpenId = model.FromUserName;
            wx_message.ReplayCont = "";
            wx_message.ReplayType = 0;
            wx_message.MsgId = model.MsgId;
            bll_wx_message.Add(wx_message);
        }
        public void m_shortvideo(int MemberId, WeChatModel.Msg_ShortVideo model) {
            //WeChatCommon.WirteFile("m_shortvideo");
            wx_message.AddTime = WxSDK.WeChatCommon.ConvertIntDateTime(model.CreateTime);
            wx_message.MemberId = MemberId;
            wx_message.MsgCont = model.MediaId;
            wx_message.MsgType = 5;
            wx_message.OpenId = model.FromUserName;
            wx_message.ReplayCont = "";
            wx_message.ReplayType = 0;
            wx_message.MsgId = model.MsgId;
            bll_wx_message.Add(wx_message);
        }
        public void m_location(int MemberId, WeChatModel.Msg_Location model) {
            //WeChatCommon.WirteFile("m_location");
            wx_message.AddTime = WxSDK.WeChatCommon.ConvertIntDateTime(model.CreateTime);
            wx_message.MemberId = MemberId;
            wx_message.MsgCont = model.Label;
            wx_message.MsgType = 6;
            wx_message.OpenId = model.FromUserName;
            wx_message.ReplayCont = "";
            wx_message.ReplayType = 0;
            wx_message.MsgId = model.MsgId;
            bll_wx_message.Add(wx_message);
        }
        public void m_link(int MemberId, WeChatModel.Msg_Link model) {
            //WeChatCommon.WirteFile("m_link");
            wx_message.AddTime = WxSDK.WeChatCommon.ConvertIntDateTime(model.CreateTime);
            wx_message.MemberId = MemberId;
            wx_message.MsgCont = model.Url;
            wx_message.MsgType = 7;
            wx_message.OpenId = model.FromUserName;
            wx_message.ReplayCont = "";
            wx_message.ReplayType = 0;
            wx_message.MsgId = model.MsgId;
            bll_wx_message.Add(wx_message);
        }
        #endregion 
    }

    /// <summary>
    /// 微信发送各种信息
    /// </summary>
    public class WeChatMsg : System.Web.UI.Page
    {
        #region 获取XML信息
        public string XmlStr = "";
        public string GetXmlInfo(string node)
        {
            return WeChatCommon.ReadXmlNode(XmlStr, "/xml/" + node);
        }
        #endregion

        #region 内部调用方法
        /// <summary>
        /// 参数构造
        /// </summary>
        private Dictionary<string, string> Parameters = new Dictionary<string, string>();
        /// <summary>
        /// 作用：array转xml
        /// </summary>
        /// <param name="arr"></param>
        /// <returns></returns>
        private string ArrayToXml(Dictionary<string, string> arr)
        {

            string xml = "<xml>";
            int fd;
            foreach (var s in arr)
            {
                if (!int.TryParse(s.Value, out fd))
                    xml += "<" + s.Key + "><![CDATA[" + s.Value + "]]></" + s.Key + ">";
                else
                    xml += "<" + s.Key + ">" + s.Value + "</" + s.Key + ">";
            }
            xml += "</xml>";
            return xml;
        }

        /// <summary>
        /// 以post方式提交xml到对应的接口url
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        private string PostDataToUrl(string url, string data)
        {
            HttpWebRequest hwr = (HttpWebRequest)HttpWebRequest.Create(url);
            hwr.Method = "POST";
            Stream stream = hwr.GetRequestStream();
            StreamWriter sw = new StreamWriter(stream, System.Text.Encoding.UTF8);
            sw.Write(data);
            sw.Close();
            stream = hwr.GetResponse().GetResponseStream();
            StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8);
            string ret = sr.ReadToEnd();
            HttpContext.Current.Response.Write(ret);
            WeChat_Pub.postvalue = ret;
            sr.Close();
            return ret;
        }

        /// <summary>
        /// 产生随机字符串，不长于32位
        /// </summary>
        /// <param name="length"></param>
        /// <returns></returns>
        private string CreatNonceStr(int length = 32)
        {
            string chars = "abcdefghijklmnopqrstuvwxyz0123456789";
            string str = "";
            var r = new Random();
            for (int i = 0; i < length; i++)
            {
                str += chars.Substring(r.Next(0, chars.Length - 1), 1);
            }
            return str;
        }

        /// <summary>
        /// 格式化参数，签名过程需要使用
        /// </summary>
        /// <param name="paraMap"></param>
        /// <returns></returns>
        private string FormatBizQueryParaMap(Dictionary<string, string> paraMap)
        {
            string buff = "";
            var al = new ArrayList(paraMap.Keys);
            al.Sort();
            foreach (string k in al)
            {
                buff += k + "=" + paraMap[k] + "&";
            }
            string reqPar = null;
            if (buff.Length > 0)
            {
                reqPar = buff.Substring(0, buff.Length - 1);
            }
            return reqPar;
        }
        /// <summary>
        /// 生成签名
        /// </summary>
        /// <param name="Obj"></param>
        /// <returns></returns>
        private string getSign(Dictionary<string, string> Obj)
        {
            Dictionary<string, string> _Parameters = new Dictionary<string, string>();
            foreach (var k in Obj)
            {
                _Parameters[k.Key] = k.Value;
            }
            string s = FormatBizQueryParaMap(Parameters);
            //echo '【string1】'.$String.'</br>';
            //签名步骤二：在string后加入KEY
            s += "&key=" + WeChatMemory.MemberInfo(WeChatConf.MemberId()).APPKEY;
            //签名步骤三：MD5加密
            s = FormsAuthentication.HashPasswordForStoringInConfigFile(s, "MD5");
            //签名步骤四：所有字符转为大写
            string result_ = s.ToUpper();
            return result_;
        }

        #endregion

        #region 获取微信消息基本属性
        #endregion

        #region 微信发送图文消息
        public Stream FileToStream(string filePath)
        {
            // 打开文件
            FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
            // 读取文件的 byte[]
            byte[] bytes = new byte[fileStream.Length];
            fileStream.Read(bytes, 0, bytes.Length);
            fileStream.Close();
            // 把 byte[] 转换成 Stream
            Stream stream = new MemoryStream(bytes);
            return stream;
        }


        /// <summary>
        /// 新增其他类型永久素材，返回值{"media_id":"eZh1QTjGGSyE-i9k8uHZqrd5LpHfYBsKtUrSfnjf8k0",
        /// "url":"http:\/\/mmbiz.qpic.cn\/mmbiz_png\/gHnmqhvpvh5HoibMEcGEAK4eAKvIR18kuKoXbjCiaRa1p1WTBgicYMDvqkjTadib21KUWYpibzfuXj6ibRw8ibw\/0?wx_fmt=png"}
        /// </summary>
        /// <param name="url">目标地址</param>
        /// <param name="path">图片物理文件路径</param>
        /// <returns></returns>
        public string add_material(string filePath,int MemberId)
        {
            //图片（image）: 2M，支持bmp/png/jpeg/jpg/gif格式
            //语音（voice）：2M，播放长度不超过60s，mp3/wma/wav/amr格式
            //视频（video）：10MB，支持MP4格式
            //缩略图（thumb）：64KB，支持JPG格式
            FileInfo fileInfo = new FileInfo(filePath);
            //var file = Request.Files[0];
            //string fileName = file.FileName;
            string fileName = fileInfo.Name;
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={0}&type={1}", WxSDK.WeChatConf.AccessToken(MemberId), "image");

            //读取上载文件流
            System.IO.Stream fileStream = FileToStream(filePath);
            byte[] fileByte = new byte[fileStream.Length];
            fileStream.Read(fileByte, 0, fileByte.Length);
            // 设置参数
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            CookieContainer cookieContainer = new CookieContainer();
            request.CookieContainer = cookieContainer;
            request.AllowAutoRedirect = true;
            request.Method = "POST";
            string boundary = DateTime.Now.Ticks.ToString("X"); // 随机分隔线
            request.ContentType = "multipart/form-data;charset=utf-8;boundary=" + boundary;
            byte[] itemBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "\r\n");
            byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");

            //请求头部信息
            StringBuilder sbHeader =
                new StringBuilder(
                    string.Format(
                        "Content-Disposition:form-data;name=\"media\";filename=\"{0}\"\r\nContent-Type:application/octet-stream\r\n\r\n",
                        fileName));
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sbHeader.ToString());
            Stream postStream = request.GetRequestStream();
            postStream.Write(itemBoundaryBytes, 0, itemBoundaryBytes.Length);
            postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
            postStream.Write(fileByte, 0, fileByte.Length);
            postStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
            postStream.Close();
            //发送请求并获取相应回应数据
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            Stream instream = response.GetResponseStream();
            StreamReader sr = new StreamReader(instream, Encoding.UTF8);
            string content = sr.ReadToEnd();
            return content;
        }


        /// <summary>
        /// 上传图文消息素材，返回格式：{"type":"news","media_id":"mF1J9boYDAQlYew4wbvbxQKMBkLPa1WzhGbDW7FVak","created_at":1391857799}
        /// </summary>TVqP_JnSHwjrxpXsyoAlLUMk3-CZdbtp1RYjU8fhMjU
        /// <returns></returns>
        public string add_news(int MemberId)
        {
            var news = "{\"articles\":[{\"thumb_media_id\":\"TVqP_JnSHwjrxpXsyoAlLY7cDWRwReDwL6jDkVD2sew\",\"author\":\"JPG\",\"title\":\"车行易.违章查询\",\"content_source_url\":\"www.qq.com\",\"content\":\"微信测试\",\"digest\":\"为车主朋友们提供优质让人满意的服务\",\"show_cover_pic\":1}]}";
            var newsUrl = "https://api.weixin.qq.com/cgi-bin/material/add_news?access_token={0}";
            newsUrl = string.Format(newsUrl, WxSDK.WeChatConf.AccessToken(MemberId));
            var result = WxSDK.WeChat_Pub.HttpPost(newsUrl, news);
            return result;
        }


        /// <summary>
        /// 预览接口(发送给指定的openId)
        /// </summary>
        /// <returns></returns>
        public string preview(int MemberId)
        {
            //说明：media_id值来自add_news接口返回值中的media_id值
            var news = "{\"touser\":\"o6TkT6P2WCjGlGPqVcX6GDBB8DqA\",\"mpnews\":{\"media_id\":\"TVqP_JnSHwjrxpXsyoAlLUMk3-CZdbtp1RYjU8fhMjU\"},\"msgtype\":\"mpnews\"}";
            var newsUrl = "https://api.weixin.qq.com/cgi-bin/message/mass/preview?access_token={0}";
            newsUrl = string.Format(newsUrl, WxSDK.WeChatConf.AccessToken(MemberId));
            var result = WxSDK.WeChat_Pub.HttpPost(newsUrl, news);
            return result;
        }


        /// <summary>
        /// 根据标签进行群发【警告，谨慎调用】
        /// </summary>
        /// <returns></returns>
        public string sendall(int MemberId)
        {
            //说明：media_id值来自add_news接口返回值中的media_id值
            var news = "{\"filter\":{\"is_to_all\":true},\"mpnews\":{\"media_id\":\"TVqP_JnSHwjrxpXsyoAlLUMk3-CZdbtp1RYjU8fhMjU\"},\"msgtype\":\"mpnews\",\"send_ignore_reprint\":0}";
            var newsUrl = "https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token={0}";
            newsUrl = string.Format(newsUrl, WxSDK.WeChatConf.AccessToken(MemberId));
            var result = WxSDK.WeChat_Pub.HttpPost(newsUrl, news);
            return result;
        }

        #endregion

        /// <summary>
        /// 回复信息 的方法
        /// </summary>
        /// <param name="Xml"></param>
        public void ReplayAllMsg(string Xml)
        {
            HttpContext.Current.Response.ContentType = "text/xml";
            HttpContext.Current.Response.ContentEncoding = System.Text.UTF8Encoding.UTF8;
            HttpContext.Current.Response.Write(Xml);
        }


        /// <summary>
        /// Post 数据  红包调用此接口
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="Data"></param>
        /// <returns></returns>
        public bool SendAllMsg(string Url, string Data)
        {
            string res = PostDataToUrl(Url, Data);
            //WeChatCommon.Log("hb", res);
            return true;
        }
        /// <summary>
        /// 发送普通接口数据
        /// </summary>
        /// <param name="Url"></param>
        /// <param name="Data"></param>
        /// <returns></returns>
        public bool PostDataToWeChat(string Url, string Data)
        {
            string res = PostDataToUrl(Url, Data);
            WeChatModel.result result = Newtonsoft.Json.JsonConvert.DeserializeObject<WeChatModel.result>(res);
            if (int.Parse(result.errcode) == 0)
            {
                return true;
            }
            else
            {
                //WeChatCommon.WeChatLog(res);
                return false;
            }
        }

        

        /// <summary>
        /// 文本消息XML
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string TxtMsgXml(WeChatModel.Msg_Txt model)
        {
            Parameters["ToUserName"] = model.ToUserName;
            Parameters["FromUserName"] = model.FromUserName;
            Parameters["CreateTime"] = model.CreateTime;
            Parameters["MsgType"] = model.MsgType;
            Parameters["Content"] = model.Content;
            return ArrayToXml(Parameters);
        }

        /// <summary>
        /// 图文消息XML
        /// </summary>
        public string TuWenXml(WeChatModel.TuWen model)
        {
            IEnumerable<Model.wx_res> Res = new WxSDK.BLL.Wx_Res().Query(0, " where Id in (" + model.Articles + ") ", " SortId desc ");
            string xml = "";
            if (Res.Count() > 0)
            {
                xml += "<xml>";
                xml += "    <ToUserName><![CDATA[" + model.ToUserName + "]]></ToUserName>";
                xml += "    <FromUserName><![CDATA[" + model.FromUserName + "]]></FromUserName>";
                xml += "    <CreateTime>" + WeChatCommon.ConvertDateTimeInt().ToString() + "</CreateTime>";
                xml += "    <MsgType><![CDATA[news]]></MsgType>";
                xml += "    <ArticleCount>" + Res.Count() + "</ArticleCount>";
                xml += "    <Articles>";
                //Model.member member = new BLL.Member().GetModel(" where WXID=@0", model.FromUserName);
                foreach (var item in Res)
                {
                    xml += "        <item>";
                    xml += "            <Title><![CDATA[" + item.Title + "]]></Title> ";
                    xml += "            <Description><![CDATA[" + item.Intro + "]]></Description>";
                    xml += "            <PicUrl><![CDATA[" + WeChatCommon.getWebConfig("WebUrl") + item.ImgUrl + "]]></PicUrl>";
                    xml += "            <Url><![CDATA[" + WeChatCommon.getWebConfig("WebUrl") + "/Article.aspx?member=" + model.FromUserName + "&res=" + item.Id + "]]></Url>";
                    xml += "        </item>";
                }
                xml += "    </Articles>";
                xml += "</xml> ";
            }
            return xml;
            //ReplayAllMsg(xml);
        }

        #region  回复信息调用接口
        /// <summary>
        /// 回复文本信息
        /// </summary>
        /// <param name="msgCont">文本信息</param>
        public void MarkTxtMsg(string msgCont)
        {
            WeChatModel.Msg_Txt Model_Msg = new WeChatModel.Msg_Txt();
            Model_Msg.FromUserName = GetXmlInfo("ToUserName");
            Model_Msg.Content = msgCont;
            Model_Msg.CreateTime = WeChatCommon.ConvertDateTimeInt().ToString();//(DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000000;
            Model_Msg.MsgType = "text";
            Model_Msg.ToUserName = GetXmlInfo("FromUserName");
            ReplayAllMsg(TxtMsgXml(Model_Msg));
        }

        public void MarkImageTxtMsg() { }


        #endregion

        /// <summary>
        /// 微信现金红包接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string RedMoneyPacketXml(WeChatModel.RedMoneyPacket model)
        {
            Parameters["mch_billno"] = model.mch_billno;
            Parameters["mch_id"] = model.mch_id;
            Parameters["wxappid"] = model.wxappid;
            Parameters["send_name"] = model.send_name;
            Parameters["re_openid"] = model.re_openid;
            Parameters["total_amount"] = model.total_amount;
            Parameters["total_num"] = model.total_num;
            Parameters["wishing"] = model.wishing;
            Parameters["client_ip"] = model.client_ip;
            Parameters["act_name"] = model.act_name;
            Parameters["remark"] = model.remark;
            Parameters["nonce_str"] = CreatNonceStr();
            Parameters["sign"] = getSign(Parameters);
            return ArrayToXml(Parameters);
        }


        /// <summary>
        /// 微信裂变红包接口
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public string RedChangePacketXml(WeChatModel.RedChangePacket model)
        {
            Parameters["mch_billno"] = model.act_name;
            Parameters["mch_id"] = model.mch_id;
            Parameters["wxappid"] = model.wxappid;
            Parameters["send_name"] = model.send_name;
            Parameters["re_openid"] = model.re_openid;
            Parameters["total_amount"] = model.total_amount;
            Parameters["amt_type"] = model.amt_type;
            Parameters["total_num"] = model.total_num;
            Parameters["wishing"] = model.wishing;
            Parameters["act_name"] = model.act_name;
            Parameters["remark"] = model.remark;
            Parameters["nonce_str"] = CreatNonceStr();
            Parameters["sign"] = getSign(Parameters);
            return ArrayToXml(Parameters);
        }


        #region 红包发送方法
        /// <summary>
        /// 发送请求
        /// </summary>
        /// <param name="data">发送拼接的参数</param>
        /// <param name="url">要发送到的链接地址</param>
        /// <returns>返回xml</returns>
        public string SendRedPacket(string url, string data)
        {
            return Send(Encoding.GetEncoding("UTF-8").GetBytes(data), url);
        }

        private static string Send(byte[] data, string url)
        {
            string cert = WeChatCommon.getWebConfig("CertPath");//证书存放的地址
            string password = WeChatCommon.getWebConfig("WX_MCHID");//证书密码 即商户号
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            X509Certificate cer = new X509Certificate(cert, password);

            #region 该部分是关键，若没有该部分则在IIS下会报 CA证书出错
            X509Certificate2 certificate = new X509Certificate2(cert, password);
            X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadWrite);
            store.Remove(certificate);   //可省略
            store.Add(certificate);
            store.Close();
            #endregion


            Stream responseStream;
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            if (request == null)
            {
                throw new ApplicationException(string.Format("Invalid url string: {0}", url));
            }
            //request.UserAgent = sUserAgent;
            //request.ContentType = sContentType;
            request.ClientCertificates.Add(cer);


            request.Method = "POST";
            request.ContentLength = data.Length;
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(data, 0, data.Length);
            requestStream.Close();
            try
            {
                responseStream = request.GetResponse().GetResponseStream();
            }
            catch (Exception exception)
            {
                throw exception;
            }
            string str = string.Empty;
            using (StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("UTF-8")))
            {
                str = reader.ReadToEnd();
            }
            responseStream.Close();
            return str;
        }
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            if (errors == SslPolicyErrors.None)
                return true;
            return false;
        }

        #endregion
    }

    /// <summary>
    /// 处理公众号的信息发送类 发送各种信息 --公众号发送客服消息,发送模板消息等
    /// </summary>
    public static class WeChatSendMsgHandle 
    { 
             
    }
    /// <summary>
    /// 处理公众号的模板消息类型
    /// </summary>
    public static class WeChatTemplateMsgHandle
    {
        //设置所属行业
        //获取行业信息
        //获取模板ID
        //获取模板列表 - 获取已添加至帐号下所有模板列表
        //wechat_location location = (wechat_location)JsonConvert.DeserializeObject(jsonData, typeof(wechat_location));
        public static void GetTemplateList(int MemberId)
        {
            string res = WeChat_Pub.HttpGet(string.Format(WxSDK.WeChat_Url.GetTemplateList, WxSDK.WeChatConf.AccessToken(MemberId)));
            WeChatModel.MsgTemplateList templateList = (WeChatModel.MsgTemplateList)JsonConvert.DeserializeObject(res, typeof(WeChatModel.MsgTemplateList));
            //WeChatModel.MsgTemplate =  templateList
            string d = templateList.template_list.Count().ToString();
            string b = d;
            //WeChatMemory.AccessToken
        }
        //发送模板
        public static string SendTemplateMsg(int MemberId, string openid, string TemplateId)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            sb.Append("\"touser\":\"" + openid + "\",");
            sb.Append("\"template_id\":\"" + TemplateId + "\",");
            sb.Append("\"url\":\"http://szyun.top\",");
            sb.Append("\"data\":{");
            sb.Append("        \"result\": {");
            sb.Append("            \"value\":\"快上车没时间解释了！\",");
            sb.Append("            \"color\":\"#ff0000\"");
            sb.Append("        },");
            sb.Append("        \"date\":{");
            sb.Append("            \"value\":\"立即发车\",");
            sb.Append("            \"color\":\"#173177\"");
            sb.Append("        },");
            sb.Append("        \"location\": {");
            sb.Append("            \"value\":\"见车就上\",");
            sb.Append("            \"color\":\"#173177\"");
            sb.Append("        },");
            sb.Append("        \"money\": {");
            sb.Append("            \"value\":\"$250.00\",");
            sb.Append("            \"color\":\"#173177\"");
            sb.Append("        },");
            sb.Append("        \"remark\":{");
            sb.Append("            \"value\":\"欢迎下次光临！\",");
            sb.Append("            \"color\":\"#173177\"");
            sb.Append("        }");
            sb.Append("}");
            sb.Append("}");

            string requesturl = string.Format(WxSDK.WeChat_Url.SendTemplateMsg, WxSDK.WeChatConf.AccessToken(MemberId));
            return WxSDK.WeChat_Pub.HttpPost(requesturl, sb.ToString());
        }
    }
    /// <summary>
    /// 处理公众号的客服消息类型
    /// </summary>
    public static class WeChatCustomerServiceMsgHandle
    {

    }

    /// <summary>
    /// 处理公众号用户发来的各种信息  消息处理程序
    /// </summary>
    public static class WeChatReciveMsgHandle
    {
        public static WxCarroit.WxSdkEvan Evan = new WxCarroit.WxSdkEvan();
        //public static WeChatMsg WeChatMsg = new WeChatMsg();
        #region 业务逻辑

        /// <summary>
        /// 收到订阅消息的处理程序
        /// </summary>
        /// <param name="MemberId">用户ID</param>
        /// <param name="MsgCont">消息内容</param>
        /// <param name="OpenId">openid</param>
        public static void ReciveSubscribeMsgHandle(WeChatMsg Msg, int MemberId)
        {
            //WeChatMsg.XmlStr = xml;
            //当前用户是否有自动回复
            WxSDK.Model.wx_member config = WeChatMemory.MemberInfo(MemberId);
            string MsgCont = Msg.GetXmlInfo("Content"); //消息内容
            string OpenId = Msg.GetXmlInfo("FromUserName"); //发送消息的用户
            //开启关注自动回复  目前只能回复文本消息
            if (config.SubReplay == 1)
            {
                switch (config.SubReplayType)
                {
                    case 1:
                        if (string.IsNullOrEmpty(config.SubReplayCont))
                        {
                            Msg.MarkTxtMsg(config.SubReplayCont);
                        }
                        break;
                    case 2:
                        Msg.MarkTxtMsg("本系统暂时不支持关注回复图片");
                        break;
                    case 3:
                        Msg.MarkTxtMsg("本系统暂时不支持关注回复语音");
                        break;
                    case 4:
                        Msg.MarkTxtMsg("本系统暂时不支持关注回复视频");
                        break;
                    case 5:
                        Msg.MarkTxtMsg("本系统暂时不支持关注回复图文");
                        break;
                    default:
                        Msg.MarkTxtMsg("未识别关注自动回复的消息类型");
                        break;
                }
                ////有自动回复
                //if (config.Study == 1)
                //{
                //    //有学习功能
                //    Msg.MarkTxtMsg("不支持图片消息 , 开启了学习功能");
                //}
                //else
                //{
                //    //没有开启学习 只开启了自动回复 //没有开启学习的话之前学习过的就不能使用
                //    Msg.MarkTxtMsg("不支持图片消息 , 未开启学习功能");
                //}

            }
        }

        /// <summary>
        /// 收到文本消息的处理程序
        /// </summary>
        /// <param name="MemberId">用户ID</param>
        /// <param name="MsgCont">消息内容</param>
        /// <param name="OpenId">openid</param>
        public static void ReciveTxtMsgHandle(WeChatMsg Msg, int MemberId)
        {
            //WeChatMsg.XmlStr = xml;
            //当前用户是否有自动回复
            WxSDK.Model.wx_member config = WeChatMemory.MemberInfo(MemberId);
            string MsgCont = Msg.GetXmlInfo("Content"); //消息内容
            string OpenId = Msg.GetXmlInfo("FromUserName"); //发送消息的用户

            //必须开启自动回复才能有学习功能 系统帮助功能等等
            if (config.AutoReplay == 1)
            {
                MsgCont = MsgCont.Trim();
                MsgCont = MsgCont.Replace("吗", "");
                MsgCont = MsgCont.Replace("?", "");
                MsgCont = MsgCont.Replace("？", "");
                Msg.MarkTxtMsg(MsgCont);
#if false
                //是否以系统关键字打头
                if (MsgCont.StartsWith(config.SysKey))
                {
                    Msg.MarkTxtMsg(GetSysReplayMsg(MsgCont, OpenId, MemberId));
                }
                else
                {
                    //有学习功能
                    if (config.Study == 1)
                    {
                        //有学习功能 2016年6月7日22:50:52 暂时关闭学习回答 
                        Msg.MarkTxtMsg(GetReplayMsg(MemberId, MsgCont, config.Study));
                        //开启机器人回复
                        //Msg.MarkTxtMsg(JuHeRobot.Robot(MsgCont, OpenId));
                    }
                    else
                    {
                        //没有开启学习 只开启了自动回复 //没有开启学习的话之前学习过的就不能使用
                        Msg.MarkTxtMsg(GetReplayMsg(MemberId, MsgCont, config.Study));
                    }
                }
#endif
            }

            //
        }

        #region 文本消息的扩展处理
        public static string GetSysReplayMsg(string msg, string openid, int MemberId)
        {
            StringBuilder sb = new StringBuilder();
            WxSDK.Model.wx_member config = WeChatMemory.MemberInfo(MemberId);
            if (msg == config.SysMenuKey)
            {
                //回复系统菜单
                sb.Append(config.SysMenu);
                //sb.Append("您好 , 智障 , 不要问我是谁 , 请看菜单 : ").Append("\n\n");
                //sb.Append("1.学习功能").Append("\n").Append("回复@study#问题#答案 , 系统会自动学习该问答");
                //sb.Append("\n\n");
                //sb.Append("回复 \"@help\" 显示此菜单");
            }
            else if (msg.StartsWith("@study"))
            {
                string[] m = msg.Split('#');
                if (string.IsNullOrEmpty(m[1]) || string.IsNullOrEmpty(m[2]))
                {
                    sb.Append("你智障吗 ? 什么都不填就让我学 ? ");
                }
                else
                {
                    if (Study(MemberId, openid, m[1], m[2])) { sb.Append("学习成功 "); }
                    else { sb.Append("学习失败 , 要不 , 再试一次 ? "); }
                }
            }
            else {
                sb.Append("未识别的指令."); 
            }
            return sb.ToString();
        }
        public static bool Study(int MemberId, string OpenId, string Q, string A)
        {
            wx_replay Replay = new wx_replay();
            Replay.MemberId = MemberId;
            Replay.IsStudy = 1;
            Replay.IsLock = 1;
            Replay.AddTime = DateTime.Now;
            Replay.AddUser = OpenId;
            Replay.MsgKey = Q;
            Replay.MsgCont = A;
            Replay.MsgType = 1;
            Replay.Rank = 1;
            Replay.RepayType = 1;
            int isok = Convert.ToInt32(Evan.Add<wx_replay>(Replay));
            return isok > 0 ? true : false;
        }
        /// <summary>
        /// 获取自动回复的内容 以及是否符合回复规则
        /// </summary>
        /// <param name="MemberId">公众号ID</param>
        /// <param name="Key">关键字</param>
        /// <param name="IsStudy">是否开启学习</param>
        /// <returns></returns>
        public static string GetReplayMsg(int MemberId, string Key, int IsStudy)
        {
            List<wx_replay> list = WeChatMemory.ReplayMsg(MemberId, IsStudy); //获取自动回复的设置列表

            list = list.FindAll(delegate(wx_replay res) { return res.MsgKey.IndexOf(Key) > -1; }); //拿到所有包含关键字的列表

            WxSDK.Model.wx_member config = WeChatMemory.MemberInfo(MemberId);  //拿到公众号配置
            if (list.Count() == 0) //如果没有触发到关键字
            {
                return config.AutoReplayCont; //默认回复
            }
            else if (list.Count() > 0) //如果有触发到关键字
            {
                Model.wx_replay replay = list[0]; //
                if (replay.Role == 0)
                {
                    return replay.MsgCont;
                }
                else {
                    if ((replay.MsgKey).IndexOf("," + Key + ",") > -1)
                    {
                        return replay.MsgCont;
                    }
                    else {
                        return config.AutoReplayCont;
                    }
                }
                //int i = Convert.ToInt32(new Random().Next(0, list.Count()));
                //多个回复随机回复
                //return list[i].MsgCont;
            }
            else
            {
                return config.AutoReplayCont;
            }
        }
        #endregion

        /// <summary>
        /// 收到图片消息的处理程序
        /// </summary>
        /// <param name="MemberId">用户ID</param>
        /// <param name="MsgCont">消息内容</param>
        /// <param name="OpenId">openid</param>
        public static void ReciveImageMsgHandle(WeChatMsg Msg, int MemberId)
        {
            //WeChatMsg.XmlStr = xml;
            //当前用户是否有自动回复
            WxSDK.Model.wx_member config = WeChatMemory.MemberInfo(MemberId);
            string MsgCont = Msg.GetXmlInfo("Content"); //消息内容
            string OpenId = Msg.GetXmlInfo("FromUserName"); //发送消息的用户
            //必须开启自动回复才能有学习功能 系统帮助功能等等
            if (config.AutoReplay == 1)
            {
                Msg.MarkTxtMsg(config.AutoReplayCont);
                ////有自动回复
                //if (config.Study == 1)
                //{
                //    //有学习功能
                //    Msg.MarkTxtMsg("不支持图片消息 , 开启了学习功能");
                //}
                //else
                //{
                //    //没有开启学习 只开启了自动回复 //没有开启学习的话之前学习过的就不能使用
                //    Msg.MarkTxtMsg("不支持图片消息 , 未开启学习功能");
                //}

            }
        }

        /// <summary>
        /// 收到语音消息的处理程序
        /// </summary>
        /// <param name="MemberId">用户ID</param>
        /// <param name="MsgCont">消息内容</param>
        /// <param name="OpenId">openid</param>
        public static void ReciveVoiceMsgHandle(WeChatMsg Msg, int MemberId)
        {
            //WeChatMsg.XmlStr = xml;
            //当前用户是否有自动回复
            WxSDK.Model.wx_member config = WeChatMemory.MemberInfo(MemberId);
            string MsgCont = Msg.GetXmlInfo("Content"); //消息内容
            string OpenId = Msg.GetXmlInfo("FromUserName"); //发送消息的用户
            //必须开启自动回复才能有学习功能 系统帮助功能等等
            if (config.AutoReplay == 1)
            {
                Msg.MarkTxtMsg(config.AutoReplayCont);
                ////有自动回复
                //if (config.Study == 1)
                //{
                //    //有学习功能
                //    Msg.MarkTxtMsg("不支持语音消息 , 开启了学习功能");
                //}
                //else
                //{
                //    //没有开启学习 只开启了自动回复 //没有开启学习的话之前学习过的就不能使用
                //    Msg.MarkTxtMsg("不支持语音消息 , 未开启学习功能");
                //}

            }
        }


        /// <summary>
        /// 收到视频消息的处理程序
        /// </summary>
        /// <param name="MemberId">用户ID</param>
        /// <param name="MsgCont">消息内容</param>
        /// <param name="OpenId">openid</param>
        public static void ReciveVideoMsgHandle(WeChatMsg Msg, int MemberId)
        {
            //WeChatMsg.XmlStr = xml;
            //当前用户是否有自动回复
            WxSDK.Model.wx_member config = WeChatMemory.MemberInfo(MemberId);
            string MsgCont = Msg.GetXmlInfo("Content"); //消息内容
            string OpenId = Msg.GetXmlInfo("FromUserName"); //发送消息的用户
            //必须开启自动回复才能有学习功能 系统帮助功能等等
            if (config.AutoReplay == 1)
            {
                Msg.MarkTxtMsg(config.AutoReplayCont);
                ////有自动回复
                //if (config.Study == 1)
                //{
                //    //有学习功能
                //    Msg.MarkTxtMsg("不支持视频消息 , 开启了学习功能");
                //}
                //else
                //{
                //    //没有开启学习 只开启了自动回复 //没有开启学习的话之前学习过的就不能使用
                //    Msg.MarkTxtMsg("不支持视频消息 , 未开启学习功能");
                //}

            }
        }


        /// <summary>
        /// 收到小视频消息的处理程序
        /// </summary>
        /// <param name="MemberId">用户ID</param>
        /// <param name="MsgCont">消息内容</param>
        /// <param name="OpenId">openid</param>
        public static void ReciveShortVideoMsgHandle(WeChatMsg Msg, int MemberId)
        {
            //WeChatMsg.XmlStr = xml;
            //当前用户是否有自动回复
            WxSDK.Model.wx_member config = WeChatMemory.MemberInfo(MemberId);
            string MsgCont = Msg.GetXmlInfo("Content"); //消息内容
            string OpenId = Msg.GetXmlInfo("FromUserName"); //发送消息的用户
            //必须开启自动回复才能有学习功能 系统帮助功能等等
            if (config.AutoReplay == 1)
            {
                Msg.MarkTxtMsg(config.AutoReplayCont);
                ////有自动回复
                //if (config.Study == 1)
                //{
                //    //有学习功能
                //    Msg.MarkTxtMsg("不支持小视频消息 , 开启了学习功能");
                //}
                //else
                //{
                //    //没有开启学习 只开启了自动回复 //没有开启学习的话之前学习过的就不能使用
                //    Msg.MarkTxtMsg("不支持小视频消息 , 未开启学习功能");
                //}

            }
        }


        /// <summary>
        /// 收到地理位置消息的处理程序
        /// </summary>
        /// <param name="MemberId">用户ID</param>
        /// <param name="MsgCont">消息内容</param>
        /// <param name="OpenId">openid</param>
        public static void ReciveLocationMsgHandle(WeChatMsg Msg, int MemberId)
        {
            //WeChatMsg.XmlStr = xml;
            //当前用户是否有自动回复
            WxSDK.Model.wx_member config = WeChatMemory.MemberInfo(MemberId);
            string MsgCont = Msg.GetXmlInfo("Content"); //消息内容
            string OpenId = Msg.GetXmlInfo("FromUserName"); //发送消息的用户
            //必须开启自动回复才能有学习功能 系统帮助功能等等
            if (config.AutoReplay == 1)
            {
                Msg.MarkTxtMsg(config.AutoReplayCont);
                ////有自动回复
                //if (config.Study == 1)
                //{
                //    //有学习功能
                //    Msg.MarkTxtMsg("不支持位置消息 , 开启了学习功能");
                //}
                //else
                //{
                //    //没有开启学习 只开启了自动回复 //没有开启学习的话之前学习过的就不能使用
                //    Msg.MarkTxtMsg("不支持位置消息 , 未开启学习功能");
                //}

            }
        }


        /// <summary>
        /// 收到链接消息的处理程序
        /// </summary>
        /// <param name="MemberId">用户ID</param>
        /// <param name="MsgCont">消息内容</param>
        /// <param name="OpenId">openid</param>
        public static void ReciveLinkMsgHandle(WeChatMsg Msg, int MemberId)
        {
            //WeChatMsg.XmlStr = xml;
            //当前用户是否有自动回复
            WxSDK.Model.wx_member config = WeChatMemory.MemberInfo(MemberId);
            string MsgCont = Msg.GetXmlInfo("Content"); //消息内容
            string OpenId = Msg.GetXmlInfo("FromUserName"); //发送消息的用户
            //必须开启自动回复才能有学习功能 系统帮助功能等等
            if (config.AutoReplay == 1)
            {
                Msg.MarkTxtMsg(config.AutoReplayCont);
                ////有自动回复
                //if (config.Study == 1)
                //{
                //    //有学习功能
                //    Msg.MarkTxtMsg("不支持链接消息 , 开启了学习功能");
                //}
                //else
                //{
                //    //没有开启学习 只开启了自动回复 //没有开启学习的话之前学习过的就不能使用
                //    Msg.MarkTxtMsg("不支持链接消息 , 未开启学习功能");
                //}

            }
        }


        /// <summary>
        /// 收到其他类型消息的处理程序
        /// </summary>
        /// <param name="MemberId">用户ID</param>
        /// <param name="MsgCont">消息内容</param>
        /// <param name="OpenId">openid</param>
        public static void ReciveOtherMsgHandle(WeChatMsg Msg, int MemberId)
        {
            //WeChatMsg.XmlStr = xml;
            //当前用户是否有自动回复
            WxSDK.Model.wx_member config = WeChatMemory.MemberInfo(MemberId);
            string MsgCont = Msg.GetXmlInfo("Content"); //消息内容
            string OpenId = Msg.GetXmlInfo("FromUserName"); //发送消息的用户
            //必须开启自动回复才能有学习功能 系统帮助功能等等
            if (config.AutoReplay == 1)
            {
                Msg.MarkTxtMsg(config.AutoReplayCont);
                ////有自动回复
                //if (config.Study == 1)
                //{
                //    //有学习功能
                //    Msg.MarkTxtMsg("不支持的消息类型 , 开启了学习功能");
                //}
                //else
                //{
                //    //没有开启学习 只开启了自动回复 //没有开启学习的话之前学习过的就不能使用
                //    Msg.MarkTxtMsg("不支持的消息类型 , 未开启学习功能");
                //}

            }
        }


        #endregion
    }

}


